package com.dtz.rabbitmq.ttl;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

import com.dtz.rabbitmq.constant.ArgsConstant;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import lombok.extern.slf4j.Slf4j;

/**
 * 设置队列中的消息统一的超时时间
 * @author 陶志胜
 *
 */
@Slf4j
public class TtlQueue {
	
	public static void main(String[] args) {
		ConnectionFactory factory = new ConnectionFactory();
		factory.setVirtualHost("/");
		factory.setHost("1.15.137.13");
		factory.setPort(5672);
		factory.setUsername("admin");
		factory.setPassword("admin");
		
		Connection connection = null;
		Channel channel = null;
		
		try {
			
			connection = factory.newConnection();
			
			channel = connection.createChannel();
			
			// 设置队列过期时间, 毫秒
			Map<String, Object> argsMap = new HashMap();
			argsMap.put(ArgsConstant.X_MESSAGE_TTL, 5000);
			
			channel.queueDeclare("ttl.queue", true, false, false, argsMap);
			
			for (int i = 0; i < 10; i++) {
				String message = i + "";
				channel.basicPublish("", "ttl.queue", null, message.getBytes());
			}
			
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		} finally {
			try {
				if (channel != null && channel.isOpen()) {
					channel.close();
				}
			} catch (IOException | TimeoutException e) {
				log.error(e.getMessage(), e);
			}
			try {
				if (connection != null && connection.isOpen()) {
					connection.close();
				}
			} catch (Exception e2) {
				log.error(e2.getMessage(), e2);
			}
		}
		
	}

}
